package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    Socket socket = null;

    public TcpEchoClient() throws IOException {
        socket = new Socket("127.0.0.1", 8080);
    }
    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("当前是客户端,请输入请求");

        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                System.out.println("> ");
                String request = sc.nextLine();
                printWriter.println(request);
                printWriter.flush();
                String response = scannerNet.nextLine();
                System.out.printf("request: %s, response: %s\n", request, response);
            }
        }  finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient();
        client.start();
    }
}
